package com.qzl.feiq.util;

import org.apache.commons.lang3.StringUtils;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class FeiQUtils {
    private static AtomicInteger packetNo = new AtomicInteger(0);

    /**
     * 获取一个唯一的数据包编号
     *
     * @return
     */
    public static int getPacketNo() {
        return packetNo.getAndIncrement();
    }

    /**
     * 获取本机IP地址
     */
    public static List<String> getLocalIpAddress() {
        ArrayList<String> iplist = new ArrayList<String>();
        Enumeration<NetworkInterface> allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
            return iplist;
        }
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    if (!ip.isLoopbackAddress()) {
                        iplist.add(ip.getHostAddress());
                    }
                }
            }
        }
        //iplist.remove("127.0.0.1");
        return iplist;
    }

    /**
     * ip 转 255.255.255.255
     *
     * @param ip
     * @return
     */
    public static String ipToBroadcast(String ip) {
        if (StringUtils.isNotBlank(ip)) {
            return ip.substring(0, ip.lastIndexOf( "."))+".255";
        }
        return null;
    }
    public static String ipSubString(String ip) {
        if (StringUtils.isNotBlank(ip)) {
            return ip.substring(0, ip.lastIndexOf( "."))+".";
        }
        return null;
    }
    public static String getNowTime() {
        return LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }
}
